import type { PageResult, PageParams, BaseResponse } from '@/types/api.d'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'

/**
 * 映射规则类型定义
 */
export interface MappingRule {
  id: number
  name: string
  sourceSystem: string
  targetSystem: string
  ruleType: 'FIELD' | 'VALUE' | 'TRANSFORM'
  sourceValue: string
  targetValue: string
  hospitalId: number
  description?: string
  isActive: boolean
  createTime: string
  updateTime: string
}

/**
 * 映射规则查询参数
 */
export interface MappingRuleSearchParams extends PageParams {
  name?: string
  sourceSystem?: string
  targetSystem?: string
  ruleType?: 'FIELD' | 'VALUE' | 'TRANSFORM'
  hospitalId?: number
  isActive?: boolean
}

/**
 * 获取映射规则列表
 * @param params 查询参数
 * @returns 分页结果
 */
export const fetchMappingRules = async (params: MappingRuleSearchParams): Promise<PageResult<MappingRule>> => {
  try {
    const { data } = await request.get<BaseResponse<PageResult<MappingRule>>>('/api/mapping-rules', { params })
    return data.data
  } catch (error) {
    ElMessage.error('获取映射规则列表失败')
    throw error
  }
}

/**
 * 获取映射规则详情
 * @param id 规则ID
 * @returns 规则详情
 */
export const getMappingRule = async (id: number): Promise<MappingRule> => {
  try {
    const { data } = await request.get<BaseResponse<MappingRule>>(`/api/mapping-rules/${id}`)
    return data.data
  } catch (error) {
    ElMessage.error('获取映射规则详情失败')
    throw error
  }
}

/**
 * 创建映射规则
 * @param data 规则数据
 * @returns 创建的规则信息
 */
export const createMappingRule = async (data: Omit<MappingRule, 'id'>): Promise<MappingRule> => {
  try {
    const { data: response } = await request.post<BaseResponse<MappingRule>>('/api/mapping-rules', data)
    ElMessage.success('创建映射规则成功')
    return response.data
  } catch (error) {
    ElMessage.error('创建映射规则失败')
    throw error
  }
}

/**
 * 更新映射规则
 * @param data 规则数据
 * @returns 更新后的规则信息
 */
export const updateMappingRule = async (data: MappingRule): Promise<MappingRule> => {
  try {
    const { data: response } = await request.put<BaseResponse<MappingRule>>(`/api/mapping-rules/${data.id}`, data)
    ElMessage.success('更新映射规则成功')
    return response.data
  } catch (error) {
    ElMessage.error('更新映射规则失败')
    throw error
  }
}

/**
 * 删除映射规则
 * @param id 规则ID
 */
export const deleteMappingRule = async (id: number): Promise<void> => {
  try {
    await request.delete(`/api/mapping-rules/${id}`)
    ElMessage.success('删除映射规则成功')
  } catch (error) {
    ElMessage.error('删除映射规则失败')
    throw error
  }
}

/**
 * 切换规则状态
 * @param id 规则ID
 * @param isActive 是否激活
 */
export const toggleMappingRuleStatus = async (id: number, isActive: boolean): Promise<void> => {
  try {
    await request.patch(`/api/mapping-rules/${id}/status`, { isActive })
    ElMessage.success(isActive ? '规则已激活' : '规则已停用')
  } catch (error) {
    ElMessage.error('切换规则状态失败')
    throw error
  }
}

// 缓存最近请求的规则数据
const mappingRuleCache = new Map<number, MappingRule>()

/**
 * 获取映射规则详情（带缓存）
 * @param id 规则ID
 * @param forceRefresh 是否强制刷新缓存
 * @returns 规则详情
 */
export const getMappingRuleWithCache = async (id: number, forceRefresh = false): Promise<MappingRule> => {
  if (!forceRefresh && mappingRuleCache.has(id)) {
    return mappingRuleCache.get(id)!
  }

  const rule = await getMappingRule(id)
  mappingRuleCache.set(id, rule)
  return rule
}
